package com.ctw.mapmycity.fb;

import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.ctw.mapmycity.auth.LoginActivity;
import com.ctw.mapmycity.model.PostModel;
import com.facebook.FacebookRequestError;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.RequestAsyncTask;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionLoginBehavior;
import com.facebook.SessionState;

public class PublishHelper {

	public static final List<String> PERMISSIONS = Arrays.asList("publish_actions");

	private static boolean checkPermission(Collection<String> subset, Collection<String> superset) {
		for (String string : subset) {
			if (!superset.contains(string)) {
				return false;
			}
		}
		return true;
	}

	public static void sharePost(final Activity activity, final PostModel postModel){
		Session session = Session.getActiveSession();
		if (session == null || !session.isOpened()){
			openFBSession(activity, postModel);
			return;
		}

		// Check for publish permissions    
		List<String> permissions = session.getPermissions();
		if (!checkPermission(PERMISSIONS, permissions)) {
			Session.NewPermissionsRequest newPermissionsRequest = 
					new Session.NewPermissionsRequest(activity, PERMISSIONS);
			session.requestNewPublishPermissions(newPermissionsRequest);
			return;
		}

		Bundle postParams = new Bundle();
		postParams.putString("name", "MAP MY CITY");
		postParams.putString("caption", postModel.getType() + " - " + postModel.getDate());
		postParams.putString("description", postModel.toString());
		postParams.putString("link", "https://developers.facebook.com/android");
		postParams.putString("picture", "http://s17.postimg.org/ru3s8qk3z/Logo_Interno.png");

		Request.Callback callback = new Request.Callback() {
			public void onCompleted(Response response) {
				JSONObject graphResponse = response.getGraphObject().getInnerJSONObject();
				String postId = null;
				try {
					postId = graphResponse.getString("id");
				} catch (JSONException e) {
					Log.i("FB PUBLISH", "JSON error "+ e.getMessage());
				}

				FacebookRequestError error = response.getError();
				if (error != null) {
					throw new RuntimeException(error.getErrorMessage());
				}else {
					Toast toast = Toast.makeText(activity.getApplicationContext(), 
							"Facebook Share realizado com sucesso", Toast.LENGTH_SHORT);
					toast.show();
				}
			}
		};

		Request request = new Request(session, "me/feed", postParams, HttpMethod.POST, callback);
		RequestAsyncTask task = new RequestAsyncTask(request);
		task.execute();
	}

	private static void openFBSession(final Activity activity, final PostModel postModel){
		Session.openActiveSession(activity, true, new Session.StatusCallback() {

			@Override
			public void call(Session session, SessionState state, Exception exception) {
				if (session.isClosed() || !session.isOpened())
					return;

				sharePost(activity, postModel);
			}
		});
	}
}